/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */

package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * <p>Project: jse2303 - Ex5</p>
 * <p>Powered by webrx On 2023-07-27 15:48:58</p>
 * <p>描述：<p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ex8 {

    List<String> list = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) {
        var e = new Ex8();
        var t = new Thread(e::add, "工作");
        var c = new Thread(e::count, "统计");
        t.start();
        c.start();
    }

    void add() {
        String t = Thread.currentThread().getName();
        System.out.printf("%s线程启动%n", t);
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String item = String.format("Item - %02d", i + 1);
            list.add(item);
            System.out.println(item);
            if (list.size() == 5) {
                latch.countDown();
            }
        }
        System.out.printf("%s线程结束%n", t);
    }

    void count() {
        String t = Thread.currentThread().getName();
        System.out.printf("%s线程启动%n", t);
        try {
            latch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.printf("%s线程,统计到5个元素%n", t);
        System.out.printf("%s线程结束%n", t);
    }
}
